<template>
  <span style="margin-left: 15px">
    <el-tooltip v-if="trDisabled" :visible="!props.applyIsDisabled" class="box-item"
                content="请先点击（处方新增）按钮后，再添加药品"
                effect="dark" placement="right">
      <el-button :disabled="!props.applyIsDisabled" plain type="primary" @click="handleAddDrug">
        <template #icon>
          <i-ep-plus/>
        </template>
        添加药品
      </el-button>
    </el-tooltip>
    <el-button v-if="trDisabled" :disabled="!props.applyIsDisabled" plain type="danger" @click="emptyDrugList(true)">
      <template #icon>
        <i-ep-delete-filled/>
      </template>
      清空
    </el-button>
  </span>

  <div style="height: 400px;overflow-y: auto;">
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-row :gutter="10" class="mt5 top-row">
        <el-form-item class="mr20" label="是否代煎" prop="isDecoction" style="margin-left: 20px">
          <el-select v-model="form.isDecoction" :disabled="!trDisabled" class="width-120"
                     placeholder="请选择">
            <el-option v-for="dict in decoctionDict" :key="dict.dictValue" :label="dict.dictLabel"
                       :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="mr20" label="途径" prop="channel">
          <administration-index :clearable="false" :disabled="!trDisabled"
                                :placeholder="'请选择途径'" :value="form.channel" class="width-120"
                                @administrationInfoChange="administrationInfoChange($event)"/>
        </el-form-item>
        <el-form-item class="mr20" label="频次" prop="performFreq">
          <perform-index ref="performIndex" :clearable="false" :disabled="!trDisabled"
                         :placeholder="'请选择频次'"
                         :value="form.performFreq" class="width-120"
                         @performFreqInfoChange="performFreqInfoChange($event)"/>
        </el-form-item>
        <el-form-item class="mr20" label="剂数" prop="repetition">
          <el-input v-model="form.repetition" :disabled="!trDisabled" clearable style="width: 60px"
                    @blur="repetitionBlur"/>
        </el-form-item>
        <el-form-item class="mr20" label="">
          共计：<span class="mr5" style="color:#ff0000;">{{ itemCount }}</span>味药材，
          总计：<span class="mr5" style="color:#ff0000;">{{ sumMoney }} </span>元
        </el-form-item>
      </el-row>
      <el-row :gutter="10" style="padding-top: 30px;margin-right: 0">
        <el-col v-for="(item, index) in form.chinesePrescriptionItemList" :key="index"
                class="div-style west-style" style="max-width: 15.5%;border-radius: 10px;">
          <div style="margin-bottom: -10px;">{{ index + 1 }}
            <el-tag v-if="trDisabled" key="1" effect="dark" round style="float: right;cursor: pointer;"
                    type="danger" @click="removeDiv(index)">
              X
            </el-tag>
            <div v-else>&nbsp;</div>
            <div class="west-style" style="margin-top: 5px">
              <el-row :gutter="0">
                <el-col :span="14">
                  <el-form-item :prop="'chinesePrescriptionItemList.' + index + '.drugName'"
                                :rules="rules.drugName" class="table-form-margin">
                    <el-popover :offset="0" :visible="visibleOpen[index]" placement="bottom"
                                popper-class="remove-popover" trigger="click" width="1190">
                      <template #reference>
                        <el-input ref="inputRef" v-model="item.drugName" :disabled="!trDisabled"
                                  :tabindex="index" placeholder="请输入需要检索的数据"
                                  @blur="itemNameBlur(index)"
                                  @focus="itemNameInput($event, index, item)"
                                  @input="itemNameInput($event, index, item)"/>
                      </template>
                      <el-table :border="true" :data="tableBodyList" height="200px"
                                highlight-current-row stripe
                                @row-click="rowClick($event, index, item)">
                        <el-table-column v-for="(item, index) in tableHeadList" :key="index"
                                         :align="item.align ? item.align : 'center'"
                                         :label="item.label"
                                         :property="item.prop" :show-overflow-tooltip="true"
                                         :width="item.width ? item.width : '90'">
                          <template #default="scope">
                                                    <span v-if="item.class === 'dict'">
                                                        <dict-data-tag :options="dictDataMap[item.dictType]"
                                                                       :value="scope.row[item.prop]"/>
                                                    </span>
                            <span v-else-if="item.class === 'date'">
                                                        <span>{{
                                                            $parseTime(scope.row[item.prop], '{y}-{m}-{d}')
                                                          }}</span>
                                                    </span>
                            <span v-else-if="item.class === 'time'">
                                                        <span>{{
                                                            $parseTime(scope.row[item.prop], '{y}-{m}-{d} {h}:{i}:{s}')
                                                          }}</span>
                                                    </span>
                            <span v-else>
                                                        <span>{{ scope.row[item.prop] }}</span>
                                                    </span>
                          </template>
                        </el-table-column>
                      </el-table>
                      <el-button style="float: right;margin-top: 5px"
                                 @click="closePopover(index)">
                        关闭
                      </el-button>
                    </el-popover>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item :prop="'chinesePrescriptionItemList.' + index + '.num'"
                                :rules="rules.num"
                                class="table-form-margin">
                    <el-input v-model="item.num" :class="'num-class' + index"
                              :disabled="!trDisabled" :tabindex="index + '-' + 1" clearable
                              placeholder="数量"
                              @blur="numBlur(index, item)">
                      <template #append>
                        g
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="0">
                <el-col :span="24">
                  <el-form-item :prop="'chinesePrescriptionItemList.' + index + '.remarks'"
                                class="table-form-margin">
                    <el-input v-model="item.remarks" :disabled="!trDisabled" clearable
                              placeholder="备注"/>
                  </el-form-item>
                </el-col>
<!--                <el-col :span="10">-->
<!--                  <el-form-item :prop="'chinesePrescriptionItemList.' + index + '.sumPrice'"-->
<!--                                :rules="rules.sumPrice" class="table-form-margin">-->
<!--                    <el-input v-model="item.sumPrice" disabled>-->
<!--                      <template #append>-->
<!--                        元-->
<!--                      </template>-->
<!--                    </el-input>-->
<!--                  </el-form-item>-->
<!--                </el-col>-->
              </el-row>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>


<script lang="ts" setup>
import {useDictStoreHook} from "@/store/modules/dict";
import {jsonStrInObj, prescriptionList} from "@/utils/autoComplete.ts";
import {positiveNumberNotNull} from "@/utils/myRules.ts";
import {listSysOrgDict} from "@/api/system/sysOrgDict.ts";
import {autoPrescriptionList} from "@/api/drug/drugStock.ts"

const emits = defineEmits(["itemSubmitOk", "submitOk", "quoteOk"])
const {proxy} = getCurrentInstance() as any;
const dictStore = useDictStoreHook();
const drugName = ref("")
let dictDataMap = ref(dictStore.isTypeGetData('spec_unit', 'sys_yes_no', 'dose_unit', 'sys_drop_speed'))
// 药品总数量
const itemCount = ref(0)
// 药品总金额
const sumMoney = ref(0.00)


//是否代煎字典
const decoctionDict = ref<any>([])
const form = ref<any>({
  isDecoction: '1',
  channel: '200',
  // 默认 一日两次
  performFreq: '978D4D8D3ACE4221B3368CD5186E1351',
  repetition: 1,
  // 药品价格list
  chinesePrescriptionItemList: []
})
const visibleOpen = ref([false,])
const formRef = ref()
const rules = ref<any>({
  drugName: [
    {required: true, message: "不能为空", trigger: "blur"}
  ],
  isDecoction: [
    {required: true, message: "代煎不能为空", trigger: "change"}
  ],
  channel: [
    {required: true, message: "用药途径不能为空", trigger: "change"}
  ],
  performFreq: [
    {required: true, message: "频次不能为空", trigger: "change"}
  ],
  num: [
    {required: true, validator: positiveNumberNotNull, trigger: "blur"}
  ],
  repetition: [
    {required: true, validator: positiveNumberNotNull, trigger: "blur"}
  ],
})
const props = defineProps({
  orgId: {
    type: String,
    default: ""
  },
  applyIsDisabled: {
    type: Boolean,
    default: true
  },
});
// 处方主信息是否禁用
const isDisabled = ref<boolean>(true)


// 项目选择自动补全窗体名称
const itemTitle = ref('选择项目')
// 项目选择自动补全表格表头
const tableHeadList = ref(jsonStrInObj(prescriptionList))
// 项目选择自动补全表格数据
const tableBodyList = ref([])
// 项目选择自动补全字典数组
const dictArray = ref(['bill_item_class_dict', 'is_medical_insurance'])

const trDisabled = ref<boolean>(false)

const autoForm = ref<any>({
  drugClassArray: "",
  storageId: "",
  itemInfo: "",
  orgId: props.orgId
})

/**
 * 数量input焦点消失事件
 * @param e
 * @param index
 * @param item
 */
function numBlur(_index: number, item: any) {
  item.sumPrice = Number((item.price * item.num).toFixed(4))
  sunUp()
}


/** 计算总金额 */
function sunUp() {
  sumMoney.value = 0.00
  itemCount.value = 0
  let sumMoneyThis = 0.00
  form.value.chinesePrescriptionItemList.forEach((item: any) => {
    sumMoneyThis += Number(item.sumPrice)
  })
  sumMoney.value = Number((sumMoneyThis * form.value.repetition).toFixed(4))
  itemCount.value = form.value.chinesePrescriptionItemList.length
}

/** 剂数焦点消失事件 */
function repetitionBlur() {
  sunUp()
}

function itemNameBlur(index: number) {
  closePopover(index)
}

function administrationInfoChange(e: any) {
  const dict = toRaw(e)
  form.value.channel = dict.dictValue
}

/**
 * 频次点击事件
 */
function performFreqInfoChange(e: any) {
  const performFreqInfo = toRaw(e)
  form.value.performFreq = performFreqInfo.freqId
  form.value.performFreqInfo = performFreqInfo
}

/**
 * 打开中药明细事件
 * @param drugClassArrayParam
 * @param storageId
 */
function setDrugClassArray(drugClassArrayParam: any, storageId: string) {
  listSysOrgDictFun()
  autoForm.value.drugClassArray = drugClassArrayParam
  autoForm.value.storageId = storageId
  trDisabled.value = true
}

function closePopover(index: number) {
  visibleOpen.value[index] = false
  // input焦点跳转到num上
  nextTick(() => {
    const nextIndex = index + '-1';
    const nextElement = document.querySelector(`[tabindex="${nextIndex}"]`);
    if (nextElement) {
      //@ts-ignore
      nextElement.focus();
    }
  });
}


/** 项目列表行点击事件 */
function rowClick(e: any, index: number, row: any) {
  row.sumPrice = 0.00
  row.singleDosageMin = e.dose
  row.singleDosage = e.dose
  row.singleUnitName = e.doseUnitsName
  row.singleUnit = e.doseUnits
  row.unitName = e.unitsName
  row.minUnits = e.minUnits
  row.packageUnits = e.packageUnits
  row.packageSpec = e.packageSpec
  row.minSpec = e.minSpec
  row.packSize = e.packSize
  row.firmName = e.firmName
  row.firmId = e.firmId
  row.drugName = e.drugName
  row.drugCode = e.drugCode
  row.price = e.price
  row.abidance = 1
  row.sumPrice = e.price * 1
  row.batchNo = e.batchNo
  row.packageNum = e.packageNum
  row.stockId = e.stockId
  row.tradePrice = e.tradePrice
  row.priceId = e.drugPriceId
  row.channel = e.channel
  row.performFreq = e.performFreq
  row.performFreqInfo = dictStore.getAppointPerformFreqInfo(e.performFreq)
  row.drugInfoId = e.drugInfoId
  row.identicalInfoId = e.identicalInfoId
  row.itemIdenticalGroup = form.value.chinesePrescriptionItemList[0].itemIdenticalGroup || "1111111111"
  if (form.value.chinesePrescriptionItemList.length > 0) {
    row.channel = form.value.chinesePrescriptionItemList[0].channel
    row.channelName = form.value.chinesePrescriptionItemList[0].channelName
    row.performFreq = form.value.chinesePrescriptionItemList[0].performFreq
    row.performFreqInfo = form.value.chinesePrescriptionItemList[0].performFreqInfo
    row.performFreqName = form.value.chinesePrescriptionItemList[0].performFreqName
  }
  row.orgId = e.orgId
  row.sort = index + 1
  tableBodyList.value = []
  closePopover(index)
}

/** 项目名称自动补全检索 */
function itemNameInput(drugName: String, index: number, item: any) {
  if (typeof drugName == "string") {
    autoForm.value.itemInfo = drugName
  } else {
    autoForm.value.itemInfo = item.drugName
  }
  getListDrugItem(index)
}

/** 自动补全后台查询 */
function getListDrugItem(index: number) {
  if (autoForm.value.itemInfo) {
    autoForm.value.orgId = props.orgId
    // 打开自动补全弹出框
    visibleOpen.value[index] = true
    autoPrescriptionList(autoForm.value).then(res => {
      tableBodyList.value = res.data
    })
  } else {
    tableBodyList.value = []
  }
}

/** 添加药品 */
function handleAddDrug() {
  (formRef.value as any).validate((valid) => {
    if (valid) {
      form.value.chinesePrescriptionItemList.push({
        // 是否免皮试 保存、修改时需要单独处理 true-> Y , false-> N
        noSkin: "Y",
        sumPrice: 0.00,
        price: 0.00,
        drugName: "",
        abidance: 1,
        num: 1
      })
      visibleOpen.value.push(false)
    }
  })
}

function emptyDrugList(type) {
  if (type) {
    ElMessageBox.confirm('重置后未保存的数据将会丢失，确定要继续操作吗？',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      emptyPrescriptionItemList()
    }).catch(() => {
      ElMessage.info("操作终止")
    })
  } else {
    emptyPrescriptionItemList()
  }
  itemCount.value = 0
  sumMoney.value = 0.00
  form.value.repetition = 1
}

function listSysOrgDictFun() {
  const param = {
    dictType: "clinic_dict",
    delFlag: "0",
    orgId: props.orgId
  }
  listSysOrgDict(param).then((res: resType) => {
    decoctionDict.value = res.data
  })
}

/**
 * 删除单个中药div
 * @param index
 */
function removeDiv(index: number) {
  ElMessageBox.confirm('确定要删除吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    form.value.chinesePrescriptionItemList.splice(index, 1)
    sunUp()
  }).catch(() => {
    ElMessage.info("操作终止")
  })
}

/**
 * 明细行数据校验
 */
function itemValidate() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      emits("itemSubmitOk", form.value)
    }
  })
}

function applyRowClick(row: any) {
  const rows = toRaw(row)
  setItemFromTemplate(rows)
}

/********************* 在处方模板菜单中调用 模板菜单中：处方模板主记录点击调用事件  **********************/
function templateMene() {
  trDisabled.value = true
}

function trDisabledInFalse() {
  trDisabled.value = false
}

// 从模板给编辑列表赋值
function setItemFromTemplate(rows: any) {
  emptyPrescriptionItemList()
  // 获取模板明细list
  const detailList = rows.detailList
  form.value.templateMasterId = rows.templateMasterId
  if (detailList.length > 0) {
    form.value.isDecoction = detailList[0].isDecoction
    form.value.repetition = detailList[0].repetition
    form.value.channel = detailList[0].channel
    form.value.performFreq = detailList[0].performFreq
  } else {
    form.value.isDecoction = "1"
    form.value.repetition = "3"
    form.value.channel = "89"
    form.value.performFreq = "水煎服"
  }
  detailList.forEach((detail: any) => {
    detail.templateMasterId = rows.templateMasterId
    detail.drugName = detail.itemName
    detail.drugCode = detail.drugCode || detail.drugCode
    detail.itemClass = detail.showItemClass
    form.value.chinesePrescriptionItemList.push(detail)
  })
  sunUp()
}

// 模板引用
function quoteRules(diagnosisList: any) {
  form.value.chinesePrescriptionItemList[0].isDecoction = form.value.isDecoction
  form.value.chinesePrescriptionItemList[0].repetition = form.value.repetition
  form.value.chinesePrescriptionItemList[0].channel = form.value.channel
  form.value.chinesePrescriptionItemList[0].performFreq = form.value.performFreq
  form.value.chinesePrescriptionItemList.forEach((item: any) => {
    item.diagnosisList = diagnosisList
  })
  emits("quoteOk", form.value.chinesePrescriptionItemList)
}

// 清空列表
function emptyPrescriptionItemList() {
  form.value.chinesePrescriptionItemList = []
}

defineExpose({
  emptyDrugList,
  setDrugClassArray,
  handleAddDrug,
  itemValidate,
  applyRowClick,
  templateMene,
  trDisabledInFalse,
  quoteRules,
  emptyPrescriptionItemList
})

</script>

<style scoped>
.west-style {
  margin: 10px 10px 10px 7px;
  padding: 0;
  background-color: #c6f4ce;
}

:deep(.el-input-group__append) {
  padding: 0 5px;
  width: 70px;
}

.top-row {
  background-color: #68e3fd;
  margin-left: 1px !important;
  height: 27px;
  position: absolute;
  z-index: 1;
  width: calc(100% - 90px);
}
</style>
